package com.ruoyi.web.controller.lucky;

import java.io.*;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.Base64Decoder;
import com.ruoyi.common.config.Global;
import com.ruoyi.lucky.domain.TBoxGoods;
import com.ruoyi.lucky.domain.TUser;
import com.ruoyi.lucky.service.ITBoxGoodsService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.lucky.domain.TGoods;
import com.ruoyi.lucky.service.ITGoodsService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品管理Controller
 * 
 * @author ruoyi
 * @date 2020-11-12
 */
@Controller
@RequestMapping("/lucky/goods")
public class TGoodsController extends BaseController
{
    private String prefix = "lucky/goods";

    @Autowired
    private ITGoodsService tGoodsService;

    @Autowired
    private ITBoxGoodsService itBoxGoodsService;


    @RequiresPermissions("lucky:goods:view")
    @GetMapping()
    public String goods()
    {
        return prefix + "/goods";
    }

    /**
     * 查询商品管理列表
     */
    @RequiresPermissions("lucky:goods:list")
    @PostMapping("/list/{id}")
    @ResponseBody
    public TableDataInfo list(@PathVariable("id") Long id, ModelMap mmap)
    {
        startPage();
        TGoods goods=new TGoods();
        goods.setBlindboxId(id);
        List<TGoods> list = tGoodsService.selectTGoodsList(goods);
        return getDataTable(list);
    }

    /**
     * 导出商品管理列表
     */
    @RequiresPermissions("lucky:goods:export")
    @Log(title = "商品管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TGoods tGoods)
    {
        List<TGoods> list = tGoodsService.selectTGoodsList(tGoods);
        ExcelUtil<TGoods> util = new ExcelUtil<TGoods>(TGoods.class);
        return util.exportExcel(list, "goods");
    }

    /**
     * 新增商品管理
     */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") Long blindboxId, ModelMap mmap)
    {
        mmap.put("blindboxId", blindboxId);
        return prefix + "/add";
    }

    /**
     * 新增保存商品管理
     */
    @RequiresPermissions("lucky:goods:add")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping("/add/{id}")
    @ResponseBody
    public AjaxResult addSave(@PathVariable("id") Long blindboxId,TGoods tGoods)
    {
        //获取商品图片编码
        String baseCode=tGoods.getGoodsPic().replace("data:image/jpeg;base64,","").replace("data:image/png;base64,","").replace("data:image/jpg;base64,","");
        String fileName= UUID.randomUUID().toString()+".jpg";
        File file = null;
        //创建文件目录
        String filePath= Global.getImageFile();
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(baseCode);
            file=new File(filePath+"/"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        tGoods.setBlindboxId(blindboxId);
        tGoods.setGoodsPic(Global.getImageAddress()+fileName);
        return toAjax(tGoodsService.insertTGoods(tGoods));
    }

    /**
     * 修改商品管理
     */
    @GetMapping("/edit/{goodsId}")
    public String edit(@PathVariable("goodsId") Long goodsId, ModelMap mmap)
    {
        TGoods tGoods = tGoodsService.selectTGoodsById(goodsId);
        mmap.put("tGoods", tGoods);
        return prefix + "/edit";
    }

    /**
     * 修改保存商品管理
     */
    @RequiresPermissions("lucky:goods:edit")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TGoods tGoods)
    {
        if(tGoods.getGoodsPic().startsWith("data")) {
            //获取商品图片编码
            String baseCode = tGoods.getGoodsPic().replace("data:image/jpeg;base64,", "").replace("data:image/png;base64,", "").replace("data:image/jpg;base64,", "");
            String fileName = UUID.randomUUID().toString() + ".jpg";
            File file = null;
            //创建文件目录
            String filePath = Global.getImageFile();
            File dir = new File(filePath);
            if (!dir.exists() && !dir.isDirectory()) {
                dir.mkdirs();
            }
            BufferedOutputStream bos = null;
            java.io.FileOutputStream fos = null;
            try {
                byte[] bytes = Base64.getDecoder().decode(baseCode);
                file = new File(filePath + "/" + fileName);
                fos = new java.io.FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
                bos.write(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            tGoods.setGoodsPic(Global.getImageAddress() + fileName);
        }
        return toAjax(tGoodsService.updateTGoods(tGoods));
    }

    /**
     * 删除商品管理
     */
    @RequiresPermissions("lucky:goods:remove")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tGoodsService.deleteTGoodsByIds(ids));
    }

    /**
     * 选择页面
     */
    @PostMapping("/addGoodsByBox")
    @ResponseBody
    public String addGoodsByBox(String idList,Long blindboxId)
    {
        try {
            String messgae = itBoxGoodsService.updateGoodsByBox(idList,blindboxId);
            return messgae;
        }catch(Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
    }

    /**
     * 返回用户
     * **/
    @ApiOperation("获取用户测试")
    @PostMapping("/demo")
    @ResponseBody
    public JSONObject demo() {
        JSONObject data=new JSONObject();
        List<TGoods> tGoods=tGoodsService.selectTGoodsList(new TGoods());
        data.put("data",tGoods);
        return data;
    }


}
